<template>
    <div>
        <div class="header">
            <h3>二、报告</h3>
            <div v-if="user_id == dispatch_id" class="operate">
                <a-button type="primary" @click="addreport = true">匹配报告</a-button>
                <a-button type="primary" @click="() => {this.showReportList = true}">上传报告</a-button>
                <input type="file" id="file" accept="application/pdf,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/msword"
                       multiple style="display: none;">
            </div>
        </div>
        <div class="form-main-content">
            <a-table :columns="columns" :dataSource="data" rowKey="id" :pagination="pagination" bordered>
                <template slot="action" slot-scope="text, record">
                    <div class="report-actions">
                        <router-link :to="'/report/update/'+record.id">
                            <img src="./../../assets/images/view.svg" alt="" title="查看"/>
                        </router-link>
                        <a @click.stop.prevent="del(record)" v-if="user_id == dispatch_id">
                            <img src="./../../assets/images/delete.svg" alt="" title="删除"/>
                        </a>
                        <a @click="exports(record.id)" class="export-icon"><img src="../../assets/images/upload.svg" title="导出" alt=""></a>
                    </div>
                </template>
            </a-table>
        </div>
        <!--添加报告-->
        <a-modal
                width="700px"
                v-model="addreport"
                title="添加巡检报告"
                @cancel="cancelSelected"
                :cancelButtonProps="{ props: {type: 'primary'}}"
                centered
                :keyboard="false"
                :maskClosable="false"
        >
            <div class="search-place">
                <a-select
                        :style="{marginBottom: '20px', width: '100%'}"
                        showSearch
                        placeholder="请输入报告信息"
                        :allowClear="true"
                        :defaultActiveFirstOption="false"
                        :showArrow="false"
                        :filterOption="false"
                        @search="searchReport"
                        @change="searchReport"
                        @select = "returnSelected"
                        :notFoundContent="null"
                >
                    <a-select-option v-for="d in reports" :key="d.id">{{d.name}}({{d.code}})</a-select-option>
                </a-select>
                <a-table  :style="{width: '650px'}" :columns="selectedColumn" :dataSource="selectedReports" :pagination="false"
                          :customRow = 'onClickRow' :rowClassName="setRowClassName" rowKey="id" bordered>
                    <template slot="action" slot-scope="text, record">
                        <a @click.stop.prevent="viewReport(record.img)">
                            <img src="./../../assets/images/view.svg" alt="" title="预览"/>
                        </a>
                    </template>
                </a-table>
            </div>
            <template slot="footer">
                <footer class="report-list-show">
                    <a-button type="primary" :disabled="!rowId" @click="saveReport">确认</a-button>
                </footer>
            </template>
        </a-modal>
        <!--删除报告-->
        <a-modal
                v-model="deleteReport"
                title="删除报告"
                @ok="sureDeleteReport"
                :cancelButtonProps="{ props: {type: 'primary'}}"
                okText="确认"
                cancelText="取消"
                centered
                :keyboard="false"
                :maskClosable="false"
        >
            <div class="confirm-delete-wrapper">
                <p>是否删除报告</p>
                <p>{{deleteData.name}}？</p>
            </div>
        </a-modal>

        <!--上传报告列表-->
        <a-modal
                v-model="showReportList"
                title="上传任务报告"
                centered
                @cancel="() => {this.fileListArr = []}"
                :keyboard="false"
                :maskClosable="false">
            <div class="review-report"><a-button type="primary" @click="startUploadReport">浏览文件</a-button></div>
            <a-table :columns="reportColumns" :dataSource="fileListArr" rowKey="id" :pagination="false" bordered>
                <template slot="action" slot-scope="text, record">
                    <div class="report-actions">
                        <a @click.stop.prevent="delReport(record)">
                            <img src="./../../assets/images/delete.svg" alt="" title="删除"/>
                        </a>
                    </div>
                </template>
            </a-table>
            <template slot="footer">
                <footer class="report-list-show">
                    <a-button type="primary" @click="promiseUpload">确认</a-button>
                </footer>
            </template>
        </a-modal>
        <a-modal
                class="progress-modal"
                v-model="showProgressList"
                title="上传任务报告"
                centered
                @cancel="() => {this.fileListArr = []; this.progress = []; this.circle = 0; this.fileList = []}"
                :footer="null"
                :keyboard="false"
                :maskClosable="false">
            <a-table :columns="progressColumns" :dataSource="fileListArr" rowKey="id" :pagination="false" bordered>
                <template slot="status" slot-scope="text, record, index">
                    <div class="report-status">
                        <div class="progress-bar" v-if="progress[index]"><a-progress :percent="parseFloat(progress[index])" /></div>
                    </div>
                </template>
                <template slot="action" slot-scope="text, record">
                    <div class="progress-actions">
                        <a @click.stop.prevent="pauseProgress">
                            <img src="./../../assets/images/pause.svg" alt="" title="暂停"/>
                        </a>
                        <a @click.stop.prevent="delProgress(record)">
                            <img src="./../../assets/images/w-delete.svg" alt="" title="删除"/>
                        </a>
                    </div>
                </template>
            </a-table>
        </a-modal>
        <!-- 预览 -->
        <a-modal :visible="previewVisible" :footer="null" @cancel="()=>this.previewVisible=false">
            <div v-if="image">
                <img style="width: 100%" :src="image"/>
            </div>
            <div>
                无统计预览
            </div>
        </a-modal>
    </div>
</template>

<script>
    import qs from "qs"
    export default {
        name: "report",
        props: ["task_id", "dispatch_id", 'order_id'],
        data() {
            return {
                user_id: this.$store.getters.user_id,
                pagination: {
                    current: 1,
                    total: 0,
                    pageSize: 10,
                    showQuickJumper: true,
                    onChange: (page, size) => {
                        this.handleChange(page, size);
                    }
                },
                columns: [
                    {title: "报告编号", dataIndex: "sn", align: "center"},
                    {title: "报告名称", dataIndex: "name", align: "center"},
                    {title: "生成时间", dataIndex: "created_at", align: "center"},
                    {title: "更新时间", dataIndex: "updated_at", align: "center"},
                    {title: "标注数量", dataIndex: "num", align: "center"},
                    {
                        title: "操作",
                        scopedSlots: {customRender: "action"},
                        align: "center"
                    }
                ],
                data: [],
                addreport: false,
                deleteReport: false,
                deleteData: {},
                reports: [],
                selectedReports: [],
                fileList: [],
                fileListArr: [],
                showReportList: false,
                showProgressList: false,
                index: 0,
                circle: 0,
                reportColumns: [
                    {title: "报告", dataIndex: "name", align: "center"},
                    {title: "大小", dataIndex: "size", align: "center"},
                    {
                        title: "操作",
                        scopedSlots: {customRender: "action"},
                        align: "center"
                    }
                ],
                progressColumns: [
                    {title: "文件名", dataIndex: "name", align: "center"},
                    {title: "大小", dataIndex: "size", align: "center"},
                    {
                        title: "状态",
                        scopedSlots: {customRender: "status"},
                        align: "center",
                        width: '100'
                    },
                    {
                        title: "操作",
                        scopedSlots: {customRender: "action"},
                        align: "center"
                    }
                ],
                progress: [],
                selectedColumn: [
                    {title: "编号", dataIndex: "code", align: "center", width: '30%'},
                    {title: "名称", dataIndex: "name", align: "center", width: '20%'},
                    {title: "生成时间", dataIndex: "addtime", align: "center", width: '20%'},
                    {title: "标注数量", dataIndex: "num", align: "center", width: '20%'},
                    {
                        title: "",
                        scopedSlots: {customRender: "action"},
                        align: "center",
                        width: '10%'
                    }
                ],
                rowId: 0,
                previewVisible:false,
                image:''
            };
        },
        methods: {
            async getList(param = {}) {
                let req = {
                    page_size: this.pagination.pageSize,
                    page: this.pagination.current,
                    task_id: this.task_id
                };

                let data = await this.http(
                    "get",
                    "report/index",
                    {...req,...param}
                );
                this.data = data.data;
                this.pagination.total = data.total_count;
            },
            del(val) {
                this.deleteData = val
                this.deleteReport = true
            },
            sureDeleteReport() {
                this.http("delete", "report/delete", {id: this.deleteData.id}).then(res => {
                    if (res.status === 'success') {
                        this.$message.success(res.msg, 1);
                        this.deleteReport = false
                        this.getList();
                    } else {
                        this.$message.error(res.msg, 1);
                    }
                }).catch(err => {
                    this.deleteReport = false
                    this.getList();
                })
            },
            searchReport(value) {
                this.http("get", "report/search", {keyword: value}).then(res => {
                    this.reports = res.data;
                });
            },
            saveReport() {
                let report = this.selectedReports.filter(item => {
                    return item.id === this.rowId
                })
                this.http("post", "report/create", {
                    report: report[0],
                    task_id: this.task_id,
                    order_id: this.order_id
                }).then(res => {
                    if (res.code == 200) {
                        this.addreport = false;
                        this.getList();
                        this.$message.success(res.msg, 1);
                    } else {
                        this.$message.error(res.msg, 1);
                    }
                    this.selectedReports = []
                    this.rowId = 0
                });
            },
            cancelSelected() {
                this.selectedReports = []
                this.rowId = 0
            },
            startUploadReport() {
                let inputNode = document.getElementById('file')
                let evt = new MouseEvent("click", {
                    bubbles: false,
                    cancelable: true,
                    view: window
                })
                inputNode.dispatchEvent(evt)

                let once = true;
                inputNode.addEventListener('change', () => {
                    if (once) {
                        let fileType = [
                            'application/pdf',
                            'application/msword',
                            'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
                        ]
                        let filteredFiles = Array.from(inputNode.files).filter(item => {
                            return fileType.indexOf(item.type) !== -1
                        })
                        this.fileList = [...this.fileList, ...filteredFiles]
                        filteredFiles.forEach(item => {
                            this.fileListArr.push({
                                id: this.index++,
                                name: item.name,
                                size: (item.size / 1024 / 1024).toFixed(3) + 'MB',
                            })
                        })
                        inputNode.value = null
                        once = false
                    }
                }, false)
            },
            delReport(report) {
                this.fileListArr.forEach((item, key) => {
                    if (item.name === report.name) {
                        this.fileList.splice(key, 1)
                        this.fileListArr.splice(key, 1)
                    }
                })
            },
            pauseProgress() {
                if (this.$store.getters.source) {
                    this.$store.getters.source.cancel('取消');
                }
            },
            delProgress(report) {
                this.fileListArr.forEach((item, key) => {
                    if (item.name === report.name) {
                        this.fileListArr.splice(key, 1)
                        this.fileList.splice(key, 1)
                        if (this.progress[key]) {
                            this.progress.splice(key, 1)
                        }
                    }
                })
            },
            async promiseUpload() {
                this.showProgressList = true
                this.showReportList = false
                for (let file of this.fileList) {
                    let formData = new FormData();

                    formData.append("files[]", file);
                    formData.append("task_id", this.task_id);
                    await this.http("post", "report/upload", formData, {}, this.uploadCallback, true).then(res => {
                        if (res.code === 200) {
                            this.fileList = []
                            this.getList()
                        } else {
                            this.$message.error(res.msg, 1)
                        }
                        this.circle++
                        if (this.$store.getters.source) {
                            this.$store.dispatch('storeSource', null);
                        }
                    }).catch(e => {
                        this.circle++
                        if (this.$store.getters.source) {
                            this.$store.dispatch('storeSource', null);
                        }
                    });
                }
            },
            uploadCallback(progressEvent) {
                this.progress[this.circle] = []
                this.progress[this.circle] = (progressEvent.loaded / progressEvent.total * 100).toFixed(2)
                this.progress = Array.from(this.progress)
            },
            returnSelected(val) {
                let list = this.selectedReports.map(item => {
                    return item['id'];
                })
                this.reports.forEach(item => {
                    if (item.id === val && list.indexOf(item.id) === -1) {
                        item.num = item.data.length
                        this.selectedReports.push(item)
                    }
                })
            },
            onClickRow(record) {
                return {
                    on: {
                        click: () => {this.rowId = record.id}
                    },
                }
            },
            setRowClassName(record) {
                return record.id === this.rowId ? 'clickRowStyle' : '';
            },
            viewReport(img) {//查看报表
                this.previewVisible = true
                this.image = img
            },
            exports(id){//导出报告
                let  params = {status:0,export:1,selects:id}
                open(process.env.VUE_APP_BASE_URL+'report/export?'+qs.stringify(params),'_blank')
            }
        },
        watch:{
            task_id(val) {
                this.getList();
            }
        },
        mounted() {
           
        }
    };
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
    @import "../../assets/scss/mixin";

    .header {
        @include fj();
        margin-bottom: 20px;

        .operate {
            margin-right: 18px;
            .ant-btn + .ant-btn {
                margin-left: 20px;
            }
        }
    }

    .report-actions {
        @include fj(space-around);
        align-items: baseline;
        .export-icon {
            padding: 5px 7px;
        }
    }

    .progress-actions {
        @include fj(space-around);
        align-items: baseline;
        a {
            color: white;
            img {
                width: 25px;
            }
        }
    }

    .report-list-show {
        @include fj(center);
        align-items: center;
    }

    .review-report {
        text-align: right;
        margin-bottom: 20px;
    }

    .report-status {
        @include fj(center);
        align-items: center;
        .progress-bar {
            width: 100px;
        }
    }

    .confirm-delete-wrapper {
        width: 100%;
        padding: 20px;
        text-align: center;
        p {
            font-size: 16px;
        }
    }

    .search-place {
        width: 250px;
    }

</style>
